﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Microsoft.Win32;

namespace UI
{
    class FilterDocManager
    {
        private string _currentFile;
        private RichTextBox _textBox;
        public FilterDocManager(RichTextBox textBox){
            _textBox = textBox;
        }
        public bool OpenDocument()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Text Document|*.txt|Filter Text|*.ftx";
            if (dlg.ShowDialog() == true)
            {
                _currentFile = dlg.FileName;
                using (Stream stream = dlg.OpenFile())
                {
                    TextRange range = new TextRange(
                        _textBox.Document.ContentStart,
                        _textBox.Document.ContentEnd
                    );
                    range.Load(stream, DataFormats.Text);
                }
                return true;
            }
            return false;
        }
        public void NewDocument()
        {
            _currentFile = null;
            _textBox.Document = new FlowDocument();
        }
        /*If you examine the File menu, you will see that the Save
command is disabled. However, if you first perform a Save As, which sets a
value for _currentFile, the command becomes available.*/
        public bool CanSaveDocument()
        {
            return !string.IsNullOrEmpty(_currentFile);
        }
        public bool SaveDocument()
        {
            if (string.IsNullOrEmpty(_currentFile)) return SaveDocumentAs();
            else
            {
                using (Stream stream =
                    new FileStream(_currentFile, FileMode.Create))
                {
                    TextRange range = new TextRange(
                    _textBox.Document.ContentStart,
                    _textBox.Document.ContentEnd
                    );
                    range.Save(stream, DataFormats.Text);
                }
                return true;
            }
        }
        public bool SaveDocumentAs()
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Filter Text|*.ftx|Text Document|*.txt";
            if (dlg.ShowDialog() == true)
            {
                _currentFile= dlg.FileName;
                return SaveDocument();
            }
            return false;
        }
        public void ApplyToSelection(DependencyProperty property, object value)
        {
            if (value != null)
                _textBox.Selection.ApplyPropertyValue(property, value);
        }
    }
}
